const mongoose = require('mongoose');
require('dotenv').config();

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/traveller_social_app', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('✅ MongoDB 连接成功');
  } catch (error) {
    console.error('❌ MongoDB 连接失败:', error);
    process.exit(1);
  }
};

// 旅游商品模型
const tourSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    trim: true
  },
  subtitle: {
    type: String,
    default: ''
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  originalPrice: {
    type: Number,
    default: null
  },
  image: {
    type: String,
    required: true
  },
  category: {
    type: String,
    required: true,
    enum: ['一日游', '多日游', '当地游', '自由行', '跟团游', '攻略群']
  },
  destination: {
    type: String,
    required: true
  },
  duration: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  highlights: [String],
  includes: [String],
  excludes: [String],
  rating: {
    type: Number,
    default: 4.5,
    min: 0,
    max: 5
  },
  reviewCount: {
    type: Number,
    default: 0
  },
  soldCount: {
    type: Number,
    default: 0
  },
  tags: [String],
  isHot: {
    type: Boolean,
    default: false
  },
  isAvailable: {
    type: Boolean,
    default: true
  },
  coordinates: {
    lat: Number,
    lng: Number
  }
}, {
  timestamps: true
});

const Tour = mongoose.model('Tour', tourSchema);

// 初始化旅游商品数据
const initializeTourData = async () => {
  try {
    // 清空现有数据
    await Tour.deleteMany({});
    console.log('🧹 清空旅游商品数据完成');

    // 创建旅游商品数据
    const tours = [
      // 一日游
      {
        title: '【8人团 包出票 可选日照金山】云南丽江玉龙雪山纯玩一日游',
        subtitle: '冰川公园+蓝月谷+甘海子',
        price: 200,
        originalPrice: 280,
        image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800',
        category: '一日游',
        destination: '云南丽江',
        duration: '1天',
        description: '玉龙雪山是纳西族人心中的神山，主峰扇子陡海拔5596米，常年积雪，雪山脚下的蓝月谷更是美不胜收。',
        highlights: ['日照金山奇观', '冰川公园索道', '蓝月谷美景', '甘海子草甸'],
        includes: ['往返交通', '门票', '索道票', '氧气瓶', '导游服务'],
        excludes: ['餐费', '个人消费'],
        rating: 4.8,
        reviewCount: 15379,
        soldCount: 28456,
        tags: ['雪山', '索道', '摄影', '纯玩'],
        isHot: true,
        coordinates: { lat: 27.1251, lng: 100.1845 }
      },
      {
        title: '【早鸟特惠】丽江香格里拉梅里雪山5日游',
        subtitle: '摄影师单反限量版',
        price: 1490,
        originalPrice: 1890,
        image: 'https://images.unsplash.com/photo-1464822759844-d150baec4e84?w=800',
        category: '多日游',
        destination: '云南香格里拉',
        duration: '5天4晚',
        description: '深入香格里拉腹地，探寻梅里雪山的神秘面纱，体验藏族文化，观赏雪山日出。',
        highlights: ['梅里雪山日出', '雨崩村徒步', '飞来寺观景', '藏族文化体验'],
        includes: ['住宿4晚', '全程用车', '门票', '导游', '部分餐食'],
        excludes: ['往返机票', '个人消费', '保险'],
        rating: 4.7,
        reviewCount: 2115,
        soldCount: 5678,
        tags: ['雪山', '徒步', '摄影', '文化'],
        isHot: true,
        coordinates: { lat: 28.4162, lng: 98.6722 }
      },
      
      // 当地游
      {
        title: '西藏林芝5日游 探索冰川秘境 豪华商务座椅',
        subtitle: '藏装拍照+南迦巴瓦峰+巴松措',
        price: 2660,
        originalPrice: 3200,
        image: 'https://images.unsplash.com/photo-1544735716-392fe2489ffa?w=800',
        category: '当地游',
        destination: '西藏林芝',
        duration: '5天4晚',
        description: '林芝被称为"西藏江南"，桃花盛开时节美如仙境，南迦巴瓦峰更是摄影爱好者的天堂。',
        highlights: ['南迦巴瓦峰', '巴松措湖', '桃花沟', '藏装体验'],
        includes: ['豪华商务车', '精品酒店', '门票', '藏装租赁', '专业导游'],
        excludes: ['往返机票', '个人消费'],
        rating: 4.6,
        reviewCount: 1889,
        soldCount: 3456,
        tags: ['雪山', '湖泊', '桃花', '摄影'],
        isHot: false,
        coordinates: { lat: 29.6544, lng: 94.3621 }
      },
      {
        title: '西藏珠峰大本营5日游 纯玩8人团',
        subtitle: '早地接发 豪华商务车 无人机航拍',
        price: 1920,
        originalPrice: 2400,
        image: 'https://images.unsplash.com/photo-1518548419970-58e3b4079ab2?w=800',
        category: '当地游',
        destination: '西藏珠峰',
        duration: '5天4晚',
        description: '前往世界之巅珠穆朗玛峰大本营，体验高原壮美风光，观赏珠峰日出日落。',
        highlights: ['珠峰大本营', '绒布寺', '珠峰日出', '无人机航拍'],
        includes: ['商务车接送', '住宿', '门票', '氧气', '专业向导'],
        excludes: ['餐费', '个人装备', '小费'],
        rating: 4.9,
        reviewCount: 8619,
        soldCount: 12345,
        tags: ['珠峰', '高原', '日出', '航拍'],
        isHot: true,
        coordinates: { lat: 27.9881, lng: 86.9250 }
      },

      // 自由行
      {
        title: '【牛蜀沟+四姑娘山2日游】含景区门票+景区美食+精美旅拍',
        subtitle: '四姑娘山户外天堂',
        price: 370,
        originalPrice: 480,
        image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800',
        category: '自由行',
        destination: '四川四姑娘山',
        duration: '2天1晚',
        description: '四姑娘山是户外爱好者的天堂，牛蜀沟风景秀丽，适合徒步和摄影。',
        highlights: ['四姑娘山全景', '牛蜀沟徒步', '高山草甸', '精美旅拍'],
        includes: ['门票', '住宿1晚', '旅拍服务', '景区美食'],
        excludes: ['交通费', '个人消费'],
        rating: 4.5,
        reviewCount: 3610,
        soldCount: 7890,
        tags: ['徒步', '摄影', '草甸', '自由行'],
        isHot: false,
        coordinates: { lat: 31.0968, lng: 102.8915 }
      },

      // 跟团游
      {
        title: '【早鸟特惠】丽江香格里拉梅里雪山5日游',
        subtitle: '摄影师单反限量版',
        price: 1490,
        originalPrice: 1890,
        image: 'https://images.unsplash.com/photo-1464822759844-d150baec4e84?w=800',
        category: '跟团游',
        destination: '云南香格里拉',
        duration: '5天4晚',
        description: '跟团深度游览香格里拉，专业摄影师带队，记录最美瞬间。',
        highlights: ['专业摄影指导', '梅里雪山', '香格里拉古城', '普达措国家公园'],
        includes: ['全程跟团', '专业摄影师', '住宿', '门票', '部分餐食'],
        excludes: ['往返交通', '个人消费'],
        rating: 4.7,
        reviewCount: 2115,
        soldCount: 4567,
        tags: ['跟团', '摄影', '雪山', '古城'],
        isHot: true,
        coordinates: { lat: 27.8269, lng: 99.7065 }
      },

      // 攻略群相关
      {
        title: '云南大理洱海环游攻略分享',
        subtitle: '实时交流有问必答',
        price: 99,
        originalPrice: 199,
        image: 'https://images.unsplash.com/photo-1544735716-392fe2489ffa?w=800',
        category: '攻略群',
        destination: '云南大理',
        duration: '攻略分享',
        description: '加入攻略群，获取最新大理洱海旅游攻略，与资深驴友交流经验。',
        highlights: ['实时攻略更新', '路线规划', '住宿推荐', '美食指南'],
        includes: ['攻略文档', '群内交流', '路线推荐', '问题解答'],
        excludes: ['实际旅行费用'],
        rating: 4.3,
        reviewCount: 892,
        soldCount: 1234,
        tags: ['攻略', '交流', '洱海', '分享'],
        isHot: false,
        coordinates: { lat: 25.6066, lng: 100.2675 }
      }
    ];

    // 批量插入数据
    const createdTours = await Tour.insertMany(tours);
    console.log('🎯 旅游商品数据初始化完成');
    console.log(`📊 创建了 ${createdTours.length} 个旅游商品`);

    // 统计各类别数量
    const categoryStats = await Tour.aggregate([
      { $group: { _id: '$category', count: { $sum: 1 } } }
    ]);
    
    console.log('\n📈 商品分类统计:');
    categoryStats.forEach(stat => {
      console.log(`   ${stat._id}: ${stat.count} 个`);
    });

    console.log('\n🎉 旅游商品数据初始化成功！');
    
  } catch (error) {
    console.error('❌ 数据初始化失败:', error);
  }
};

// 运行初始化
const runInit = async () => {
  await connectDB();
  await initializeTourData();
  await mongoose.connection.close();
  console.log('👋 数据库连接已关闭');
};

// 如果直接运行此文件
if (require.main === module) {
  runInit();
}

module.exports = { initializeTourData, Tour }; 